// 全局变量
let originalPlan = null;
let stepPlan = null;

// DOM元素
let generatePlanBtn;
let generateStepPlanBtn;
let compareAnalysisBtn;
let originalPlanDiv;
let stepPlanDiv;
let comparisonSection;
let comparisonResult;

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    generatePlanBtn = document.getElementById('generatePlan');
    generateStepPlanBtn = document.getElementById('generateStepPlan');
    compareAnalysisBtn = document.getElementById('compareAnalysis');
    originalPlanDiv = document.getElementById('originalPlan');
    stepPlanDiv = document.getElementById('stepPlan');
    comparisonSection = document.getElementById('comparisonSection');
    comparisonResult = document.getElementById('comparisonResult');
    

    
    // 绑定事件监听器
    generatePlanBtn.addEventListener('click', generateOriginalPlan);
    generateStepPlanBtn.addEventListener('click', generateStepPlan);
    compareAnalysisBtn.addEventListener('click', compareAnalysis);
    
    // 下载按钮
    document.getElementById('downloadBtn').addEventListener('click', downloadPlan);
    
    // 设置默认值
    document.getElementById('loanAmount').value = '40000';
    document.getElementById('loanTerm').value = '3';
    document.getElementById('annualRate').value = '15.20';
    document.getElementById('stepRatio').value = '8.00:2.00';
    document.getElementById('stepAnnualRate').value = '18.06';
    
    // 绑定验证事件
    document.getElementById('loanAmount').addEventListener('input', validateInputs);
    document.getElementById('annualRate').addEventListener('input', validateInputs);
    document.getElementById('stepRatio').addEventListener('input', validateStepRatio);
    document.getElementById('stepAnnualRate').addEventListener('input', validateStepRatio);
    
    // 绑定阶梯类别选择事件
    document.getElementById('stepType').addEventListener('change', updateStepRatioPlaceholder);
    
    // 初始化阶梯类别
    updateStepRatioPlaceholder();
    
    // 初始化按钮状态
    validateInputs();
    validateStepRatio();
});

// 生成原始还款计划
function generateOriginalPlan() {
    const loanAmount = parseFloat(document.getElementById('loanAmount').value);
    const annualRate = parseFloat(document.getElementById('annualRate').value) / 100;
    const repaymentMethod = document.getElementById('repaymentMethod').value;
    const loanTerm = parseInt(document.getElementById('loanTerm').value);
    
    if (!loanAmount || !annualRate || !loanTerm) {
        alert('请填写完整的贷款信息');
        return;
    }
    
    const monthlyRate = annualRate / 12;
    const totalMonths = loanTerm * 12;
    
    let plan = [];
    
    if (repaymentMethod === 'equal') {
        // 等额本息
        const monthlyPayment = loanAmount * (monthlyRate * Math.pow(1 + monthlyRate, totalMonths)) / 
                              (Math.pow(1 + monthlyRate, totalMonths) - 1);
        
        let remainingPrincipal = loanAmount;
        for (let month = 1; month <= totalMonths; month++) {
            const interest = remainingPrincipal * monthlyRate;
            const principal = monthlyPayment - interest;
            remainingPrincipal -= principal;
            
            plan.push({
                month: month,
                payment: monthlyPayment,
                principal: principal,
                interest: interest,
                remainingPrincipal: Math.max(0, remainingPrincipal)
            });
        }
    } else {
        // 等额本金
        const monthlyPrincipal = loanAmount / totalMonths;
        
        for (let month = 1; month <= totalMonths; month++) {
            const remainingPrincipal = loanAmount - (month - 1) * monthlyPrincipal;
            const interest = remainingPrincipal * monthlyRate;
            const payment = monthlyPrincipal + interest;
            
            plan.push({
                month: month,
                payment: payment,
                principal: monthlyPrincipal,
                interest: interest,
                remainingPrincipal: Math.max(0, remainingPrincipal - monthlyPrincipal)
            });
        }
    }
    
    originalPlan = plan;
    displayPlan(originalPlanDiv, plan, '原方案');
    
    // 滚动到还款计划区域
    document.querySelector('.plans-container').scrollIntoView({ behavior: 'smooth' });
    
    if (stepPlan) {
        compareAnalysisBtn.disabled = false;
        // 如果对比分析已经存在，自动触发对比分析
        if (comparisonSection.style.display !== 'none') {
            compareAnalysis();
        }
    }
}

// 生成阶梯贷方案
function generateStepPlan() {
    if (!originalPlan) {
        alert('请先生成原始还款计划');
        return;
    }
    
    // 根据阶梯类别生成新方案数据
    const stepType = document.getElementById('stepType').value;
    const stepRatio = document.getElementById('stepRatio').value;
    const ratios = stepRatio.split(':').map(r => parseFloat(r.trim()));
    
    let stepPlanData;
    
    if (stepType === 'two') {
        // 两阶：前两年和后一年
        stepPlanData = generateTwoStagePlan(ratios);
    } else {
        // 三阶：每年为一阶
        stepPlanData = generateThreeStagePlan(ratios);
    }
    
    stepPlan = stepPlanData;
    
    // 显示新方案
    displayStepPlan(stepPlanDiv, stepPlanData, '阶梯贷方案');
    
    // 滚动到还款计划区域
    document.querySelector('.plans-container').scrollIntoView({ behavior: 'smooth' });
    
    if (originalPlan) {
        compareAnalysisBtn.disabled = false;
        // 如果对比分析已经存在，自动触发对比分析
        if (comparisonSection.style.display !== 'none') {
            compareAnalysis();
        }
    }
}

// 显示还款计划
function displayPlan(container, plan, title) {
    if (!plan || plan.length === 0) {
        container.innerHTML = '<p class="no-data">暂无数据</p>';
        return;
    }
    
    let html = `
        <table class="repayment-table">
            <thead>
                <tr>
                    <th>期数</th>
                    <th>还款金额</th>
                    <th>本金</th>
                    <th>利息</th>
                    <th>剩余本金</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    // 收起状态：只显示前5期和后5期，中间显示省略信息
    const totalPeriods = plan.length;
    const displayPeriods = 10; // 显示10期（前5期+后5期）
    
    if (totalPeriods <= displayPeriods) {
        // 如果总期数不超过10期，全部显示
        plan.forEach(item => {
            html += `
                <tr>
                    <td>${item.month}</td>
                    <td>¥${item.payment.toFixed(2)}</td>
                    <td>¥${item.principal.toFixed(2)}</td>
                    <td>¥${item.interest.toFixed(2)}</td>
                    <td>¥${item.remainingPrincipal.toFixed(2)}</td>
                </tr>`;
        });
    } else {
        // 显示前5期
        for (let i = 0; i < 5; i++) {
            const item = plan[i];
            html += `
                <tr>
                    <td>${item.month}</td>
                    <td>¥${item.payment.toFixed(2)}</td>
                    <td>¥${item.principal.toFixed(2)}</td>
                    <td>¥${item.interest.toFixed(2)}</td>
                    <td>¥${item.remainingPrincipal.toFixed(2)}</td>
                </tr>`;
        }
        
        // 添加省略号行
        const omittedPeriods = totalPeriods - 10;
        html += `
            <tr class="ellipsis-row">
                <td colspan="5" style="text-align: center; color: #666; font-style: italic;">
                    ... 省略 ${omittedPeriods} 期 ...
                </td>
            </tr>`;
        
        // 显示后5期
        for (let i = totalPeriods - 5; i < totalPeriods; i++) {
            const item = plan[i];
            html += `
                <tr>
                    <td>${item.month}</td>
                    <td>¥${item.payment.toFixed(2)}</td>
                    <td>¥${item.principal.toFixed(2)}</td>
                    <td>¥${item.interest.toFixed(2)}</td>
                    <td>¥${item.remainingPrincipal.toFixed(2)}</td>
                </tr>`;
        }
    }
    
    // 计算合计数据
    const totalPayment = plan.reduce((sum, item) => sum + item.payment, 0);
    const totalPrincipal = plan.reduce((sum, item) => sum + item.principal, 0);
    const totalInterest = plan.reduce((sum, item) => sum + item.interest, 0);
    
    // 添加合计行
    html += `
        <tr class="total-row">
            <td><strong>合计</strong></td>
            <td><strong>¥${totalPayment.toFixed(2)}</strong></td>
            <td><strong>¥${totalPrincipal.toFixed(2)}</strong></td>
            <td><strong>¥${totalInterest.toFixed(2)}</strong></td>
            <td><strong>-</strong></td>
        </tr>
    `;
    
    html += '</tbody></table>';
    
    container.innerHTML = html;
    
    // 更新标题，添加还款方式和年化利率
    const planSection = container.closest('.plan-section');
    const titleElement = planSection.querySelector('h3');
    const repaymentMethod = document.getElementById('repaymentMethod');
    const annualRate = document.getElementById('annualRate').value;
    const repaymentMethodText = repaymentMethod.options[repaymentMethod.selectedIndex].text;
    
    titleElement.innerHTML = `常规贷款方案 <span class="title-info">(${repaymentMethodText} · ${annualRate}%)</span>`;
    
    // 显示展开/收起按钮
    const controls = planSection.querySelector('.plan-controls');
    if (controls && totalPeriods > displayPeriods) {
        controls.style.display = 'block';
    }
}

// 展开/收起还款计划显示
function togglePlanDisplay(planId) {
    const container = document.getElementById(planId);
    const planSection = container.closest('.plan-section');
    const controls = planSection.querySelector('.plan-controls');
    const expandBtn = controls.querySelector('.expand-btn');
    const expandText = controls.querySelector('.expand-text');
    const expandIcon = controls.querySelector('.expand-icon');
    
    if (container.classList.contains('expanded')) {
        // 收起：只显示前5期和后5期
        container.classList.remove('expanded');
        expandText.textContent = '展开全部';
        expandIcon.textContent = '▼';
        expandBtn.classList.remove('expanded');
        
        // 重新调用displayPlan来显示缩略版本
        if (planId === 'originalPlan' && originalPlan) {
            displayPlan(container, originalPlan, '原方案');
        } else if (planId === 'stepPlan' && stepPlan) {
            displayStepPlan(container, stepPlan, '阶梯贷方案');
        }
    } else {
        // 展开：显示全部期数
        container.classList.add('expanded');
        expandText.textContent = '收起';
        expandIcon.textContent = '▲';
        expandBtn.classList.add('expanded');
        
        // 显示完整的还款计划
        if (planId === 'originalPlan' && originalPlan) {
            displayFullPlan(container, originalPlan, '原方案');
        } else if (planId === 'stepPlan' && stepPlan) {
            displayFullStepPlan(container, stepPlan, '阶梯贷方案');
        }
    }
}

// 显示完整的还款计划（全部期数）
function displayFullPlan(container, plan, title) {
    if (!plan || plan.length === 0) {
        container.innerHTML = '<p class="no-data">暂无数据</p>';
        return;
    }
    
    let html = `
        <table class="repayment-table">
            <thead>
                <tr>
                    <th>期数</th>
                    <th>还款金额</th>
                    <th>本金</th>
                    <th>利息</th>
                    <th>剩余本金</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    // 显示全部期数
    plan.forEach(item => {
        html += `
            <tr>
                <td>${item.month}</td>
                <td>¥${item.payment.toFixed(2)}</td>
                <td>¥${item.principal.toFixed(2)}</td>
                <td>¥${item.interest.toFixed(2)}</td>
                <td>¥${item.remainingPrincipal.toFixed(2)}</td>
            </tr>`;
    });
    
    // 计算合计数据
    const totalPayment = plan.reduce((sum, item) => sum + item.payment, 0);
    const totalPrincipal = plan.reduce((sum, item) => sum + item.principal, 0);
    const totalInterest = plan.reduce((sum, item) => sum + item.interest, 0);
    
    // 添加合计行
    html += `
        <tr class="total-row">
            <td><strong>合计</strong></td>
            <td><strong>¥${totalPayment.toFixed(2)}</strong></td>
            <td><strong>¥${totalPrincipal.toFixed(2)}</strong></td>
            <td><strong>¥${totalInterest.toFixed(2)}</strong></td>
            <td><strong>-</strong></td>
        </tr>
    `;
    
    html += '</tbody></table>';
    
    container.innerHTML = html;
    
    // 更新标题，添加还款方式和年化利率
    const planSection = container.closest('.plan-section');
    const titleElement = planSection.querySelector('h3');
    const repaymentMethod = document.getElementById('repaymentMethod');
    const annualRate = document.getElementById('annualRate').value;
    const repaymentMethodText = repaymentMethod.options[repaymentMethod.selectedIndex].text;
    
    titleElement.innerHTML = `常规贷款方案 <span class="title-info">(${repaymentMethodText} · ${annualRate}%)</span>`;
}

// 显示完整的阶梯贷还款计划（全部期数）
function displayFullStepPlan(container, plan, title) {
    if (!plan || plan.length === 0) {
        container.innerHTML = '<p class="no-data">暂无数据</p>';
        return;
    }
    
    let html = `
        <table class="repayment-table">
            <thead>
                <tr>
                    <th>期数</th>
                    <th>还款金额</th>
                    <th>本金</th>
                    <th>利息</th>
                    <th>剩余本金</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    // 显示全部期数
    plan.forEach(item => {
        html += `
            <tr>
                <td>${item.month}</td>
                <td>¥${item.payment.toFixed(2)}</td>
                <td>¥${item.principal.toFixed(2)}</td>
                <td>¥${item.interest.toFixed(2)}</td>
                <td>¥${item.remainingPrincipal.toFixed(2)}</td>
            </tr>`;
    });
    
    // 计算合计数据
    const totalPayment = plan.reduce((sum, item) => sum + item.payment, 0);
    const totalPrincipal = plan.reduce((sum, item) => sum + item.principal, 0);
    const totalInterest = plan.reduce((sum, item) => sum + item.interest, 0);
    
    // 添加合计行
    html += `
        <tr class="total-row">
            <td><strong>合计</strong></td>
            <td><strong>¥${totalPayment.toFixed(2)}</strong></td>
            <td><strong>¥${totalPrincipal.toFixed(2)}</strong></td>
            <td><strong>¥${totalInterest.toFixed(2)}</strong></td>
            <td><strong>-</strong></td>
        </tr>
    `;
    
    html += '</tbody></table>';
    
    container.innerHTML = html;
    
    // 更新标题，添加还款方式、年化利率、阶梯类别、阶梯比例
    const planSection = container.closest('.plan-section');
    const titleElement = planSection.querySelector('h3');
    const repaymentMethod = document.getElementById('repaymentMethod');
    const stepAnnualRate = document.getElementById('stepAnnualRate').value;
    const stepType = document.getElementById('stepType');
    const stepRatio = document.getElementById('stepRatio').value;
    const repaymentMethodText = repaymentMethod.options[repaymentMethod.selectedIndex].text;
    const stepTypeText = stepType.options[stepType.selectedIndex].text;
    
    titleElement.innerHTML = `阶梯贷方案 <span class="title-info">(${repaymentMethodText} · ${stepAnnualRate}% · ${stepTypeText} · ${stepRatio})</span>`;
}

// 显示阶梯贷还款计划
function displayStepPlan(container, plan, title) {
    if (!plan || plan.length === 0) {
        container.innerHTML = '<p class="no-data">暂无数据</p>';
        return;
    }
    
    let html = `
        <table class="repayment-table">
            <thead>
                <tr>
                    <th>期数</th>
                    <th>还款金额</th>
                    <th>本金</th>
                    <th>利息</th>
                    <th>剩余本金</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    // 收起状态：只显示前5期和后5期，中间显示省略信息
    const totalPeriods = plan.length;
    const displayPeriods = 10; // 显示10期（前5期+后5期）
    
    if (totalPeriods <= displayPeriods) {
        // 如果总期数不超过10期，全部显示
        plan.forEach(item => {
            html += `
                <tr>
                    <td>${item.month}</td>
                    <td>¥${item.payment.toFixed(2)}</td>
                    <td>¥${item.principal.toFixed(2)}</td>
                    <td>¥${item.interest.toFixed(2)}</td>
                    <td>¥${item.remainingPrincipal.toFixed(2)}</td>
                </tr>`;
        });
    } else {
        // 显示前5期
        for (let i = 0; i < 5; i++) {
            const item = plan[i];
            html += `
                <tr>
                    <td>${item.month}</td>
                    <td>¥${item.payment.toFixed(2)}</td>
                    <td>¥${item.principal.toFixed(2)}</td>
                    <td>¥${item.interest.toFixed(2)}</td>
                    <td>¥${item.remainingPrincipal.toFixed(2)}</td>
                </tr>`;
        }
        
        // 添加省略号行
        const omittedPeriods = totalPeriods - 10;
        html += `
            <tr class="ellipsis-row">
                <td colspan="5" style="text-align: center; color: #666; font-style: italic;">
                    ... 省略 ${omittedPeriods} 期 ...
                </td>
            </tr>`;
        
        // 显示后5期
        for (let i = totalPeriods - 5; i < totalPeriods; i++) {
            const item = plan[i];
            html += `
                <tr>
                    <td>${item.month}</td>
                    <td>¥${item.payment.toFixed(2)}</td>
                    <td>¥${item.principal.toFixed(2)}</td>
                    <td>¥${item.interest.toFixed(2)}</td>
                    <td>¥${item.remainingPrincipal.toFixed(2)}</td>
                </tr>`;
        }
    }
    
    // 计算合计数据
    const totalPayment = plan.reduce((sum, item) => sum + item.payment, 0);
    const totalPrincipal = plan.reduce((sum, item) => sum + item.principal, 0);
    const totalInterest = plan.reduce((sum, item) => sum + item.interest, 0);
    
    // 添加合计行
    html += `
        <tr class="total-row">
            <td><strong>合计</strong></td>
            <td><strong>¥${totalPayment.toFixed(2)}</strong></td>
            <td><strong>¥${totalPrincipal.toFixed(2)}</strong></td>
            <td><strong>¥${totalInterest.toFixed(2)}</strong></td>
            <td><strong>-</strong></td>
        </tr>
    `;
    
    html += '</tbody></table>';
    
    container.innerHTML = html;
    
    // 更新标题，添加还款方式、年化利率、阶梯类别、阶梯比例
    const planSection = container.closest('.plan-section');
    const titleElement = planSection.querySelector('h3');
    const repaymentMethod = document.getElementById('repaymentMethod');
    const stepAnnualRate = document.getElementById('stepAnnualRate').value;
    const stepType = document.getElementById('stepType');
    const stepRatio = document.getElementById('stepRatio').value;
    const repaymentMethodText = repaymentMethod.options[repaymentMethod.selectedIndex].text;
    const stepTypeText = stepType.options[stepType.selectedIndex].text;
    
    titleElement.innerHTML = `阶梯贷方案 <span class="title-info">(${repaymentMethodText} · ${stepAnnualRate}% · ${stepTypeText} · ${stepRatio})</span>`;
    
    // 显示展开/收起按钮
    const controls = planSection.querySelector('.plan-controls');
    if (controls && plan.length > 10) {
        controls.style.display = 'block';
    }
}



// 计算资金使用率提升
function calculateFundUtilizationImprovement(originalPlan, stepPlan) {
    // 前两年（24期）的资金回收率提升
    const originalFirstTwoYears = originalPlan.slice(0, 24).reduce((sum, item) => sum + item.payment, 0);
    const stepFirstTwoYears = stepPlan.slice(0, 24).reduce((sum, item) => sum + item.payment, 0);
    
    const originalTotal = originalPlan.reduce((sum, item) => sum + item.payment, 0);
    const stepTotal = stepPlan.reduce((sum, item) => sum + item.payment, 0);
    
    const originalRatio = (originalFirstTwoYears / originalTotal) * 100;
    const stepRatio = (stepFirstTwoYears / stepTotal) * 100;
    
    return stepRatio - originalRatio;
}

// 计算第一年资金使用率变化
function calculateFirstYearFundUtilizationChange(originalPlan, stepPlan) {
    // 第一年（12期）的资金回收率变化
    const originalFirstYear = originalPlan.slice(0, 12).reduce((sum, item) => sum + item.payment, 0);
    const stepFirstYear = stepPlan.slice(0, 12).reduce((sum, item) => sum + item.payment, 0);
    
    const originalTotal = originalPlan.reduce((sum, item) => sum + item.payment, 0);
    const stepTotal = stepPlan.reduce((sum, item) => sum + item.payment, 0);
    
    const originalRatio = (originalFirstYear / originalTotal) * 100;
    const stepRatio = (stepFirstYear / stepTotal) * 100;
    
    return stepRatio - originalRatio;
}

// 计算风险降低程度
function calculateRiskReduction(originalPlan, stepPlan) {
    // 计算前两年（24期）的利息回收比例
    // 这个比例越高，说明在贷款前期就回收了更多利息，降低了后期风险
    const originalFirstTwoYearsInterest = originalPlan.slice(0, 24).reduce((sum, item) => sum + item.interest, 0);
    const stepFirstTwoYearsInterest = stepPlan.slice(0, 24).reduce((sum, item) => sum + item.interest, 0);
    
    const originalTotalInterest = originalPlan.reduce((sum, item) => sum + item.interest, 0);
    const stepTotalInterest = stepPlan.reduce((sum, item) => sum + item.interest, 0);
    
    // 前两年利息回收比例
    const originalRatio = (originalFirstTwoYearsInterest / originalTotalInterest) * 100;
    const stepRatio = (stepFirstTwoYearsInterest / stepTotalInterest) * 100;
    
    // 风险降低程度 = 新方案前两年利息回收比例 - 原方案前两年利息回收比例
    // 正数表示风险降低，负数表示风险增加
    return stepRatio - originalRatio;
}

// 计算本金回收比例变化
function calculatePrincipalRecoveryChange(originalPlan, stepPlan) {
    // 计算前两年（24期）的本金回收比例
    // 这个比例越高，说明在贷款前期就回收了更多本金，降低了后期风险
    const originalFirstTwoYearsPrincipal = originalPlan.slice(0, 24).reduce((sum, item) => sum + item.principal, 0);
    const stepFirstTwoYearsPrincipal = stepPlan.slice(0, 24).reduce((sum, item) => sum + item.principal, 0);
    
    const originalTotalPrincipal = originalPlan.reduce((sum, item) => sum + item.principal, 0);
    const stepTotalPrincipal = stepPlan.reduce((sum, item) => sum + item.principal, 0);
    
    // 前两年本金回收比例
    const originalRatio = (originalFirstTwoYearsPrincipal / originalTotalPrincipal) * 100;
    const stepRatio = (stepFirstTwoYearsPrincipal / stepTotalPrincipal) * 100;
    
    // 本金回收比例变化 = 新方案前两年本金回收比例 - 原方案前两年本金回收比例
    // 正数表示本金回收比例提升，负数表示本金回收比例下降
    return stepRatio - originalRatio;
}





// 对比分析
function compareAnalysis() {
    if (!originalPlan || !stepPlan) {
        alert('请先生成两个还款方案');
        return;
    }
    
    const originalTotal = originalPlan.reduce((sum, item) => sum + item.payment, 0);
    const originalInterest = originalPlan.reduce((sum, item) => sum + item.interest, 0);
    const originalMonthlyAvg = originalTotal / originalPlan.length;
    const originalRate = parseFloat(document.getElementById('annualRate').value);
    
    const stepTotal = stepPlan.reduce((sum, item) => sum + item.payment, 0);
    const stepInterest = stepPlan.reduce((sum, item) => sum + item.interest, 0);
    const stepMonthlyAvg = stepTotal / stepPlan.length;
    
    // 获取阶梯贷年化利率
    const stepAnnualRate = parseFloat(document.getElementById('stepAnnualRate').value);
    
    const comparisonHTML = `
            <div class="comparison-group">
                <div class="comparison-data">
                    <h4>总利息变化</h4>
                    <div class="comparison-value ${(stepInterest - originalInterest) >= 0 ? '' : 'negative'}">${(stepInterest - originalInterest) >= 0 ? '+' : ''}${(stepInterest - originalInterest).toFixed(2)}元</div>
                    <div class="comparison-desc">相比原方案总利息变化</div>
                </div>
                <div class="comparison-method">
                    <strong>计算方法：</strong>
                    <div class="formula">变化金额 = 阶梯贷总利息 - 原方案总利息</div>
                    <div class="detail">直接比较两个方案的总利息差异，正数表示利息增加，负数表示利息减少</div>
                </div>
            </div>
            
            <div class="comparison-group">
                <div class="comparison-data">
                    <h4>年化利率变化</h4>
                    <div class="comparison-value ${(stepAnnualRate - originalRate) >= 0 ? '' : 'negative'}">${(stepAnnualRate - originalRate) >= 0 ? '+' : ''}${(stepAnnualRate - originalRate).toFixed(2)}%</div>
                    <div class="comparison-desc">相比原方案利率变化</div>
                </div>
                <div class="comparison-method">
                    <strong>计算方法：</strong>
                    <div class="formula">变化率 = 阶梯贷年化利率 - 原方案年化利率</div>
                    <div class="detail">直接比较两个方案的年化利率差异</div>
                </div>
            </div>
            
            <div class="comparison-group">
                <div class="comparison-data">
                    <h4>资金使用率变化</h4>
                    <div class="data-row">
                        <div class="data-item">
                            <div class="comparison-value ${calculateFirstYearFundUtilizationChange(originalPlan, stepPlan) >= 0 ? '' : 'negative'}">${calculateFirstYearFundUtilizationChange(originalPlan, stepPlan) >= 0 ? '+' : ''}${calculateFirstYearFundUtilizationChange(originalPlan, stepPlan).toFixed(1)}%</div>
                            <div class="comparison-desc">第一年资金回收率变化</div>
                        </div>
                        <div class="data-item">
                            <div class="comparison-value ${calculateFundUtilizationImprovement(originalPlan, stepPlan) >= 0 ? '' : 'negative'}">${calculateFundUtilizationImprovement(originalPlan, stepPlan) >= 0 ? '+' : ''}${calculateFundUtilizationImprovement(originalPlan, stepPlan).toFixed(1)}%</div>
                            <div class="comparison-desc">前两年资金回收率变化</div>
                        </div>
                    </div>
                </div>
                <div class="comparison-method">
                    <strong>计算方法：</strong>
                    <div class="formula">变化率 = (阶梯贷还款占比 - 原方案还款占比) × 100%</div>
                    <div class="detail">还款占比 = 对应期数还款总额 ÷ 总还款总额 × 100%</div>
                </div>
            </div>
            
            <div class="comparison-group">
                <div class="comparison-data">
                    <h4>风险降低程度</h4>
                    <div class="data-row">
                        <div class="data-item">
                            <div class="comparison-value ${calculateRiskReduction(originalPlan, stepPlan) >= 0 ? '' : 'negative'}">${calculateRiskReduction(originalPlan, stepPlan) >= 0 ? '+' : ''}${calculateRiskReduction(originalPlan, stepPlan).toFixed(1)}%</div>
                            <div class="comparison-desc">前两年利息回收比例提升</div>
                        </div>
                        <div class="data-item">
                            <div class="comparison-value ${calculatePrincipalRecoveryChange(originalPlan, stepPlan) >= 0 ? '' : 'negative'}">${calculatePrincipalRecoveryChange(originalPlan, stepPlan) >= 0 ? '+' : ''}${calculatePrincipalRecoveryChange(originalPlan, stepPlan).toFixed(1)}%</div>
                            <div class="comparison-desc">前两年本金回收比例提升</div>
                        </div>
                    </div>
                </div>
                <div class="comparison-method">
                    <strong>计算方法：</strong>
                    <div class="formula">降低率 = (阶梯贷前两年占比 - 原方案前两年占比) × 100%</div>
                    <div class="detail">前两年占比越高，说明前期回收资金越多，后期风险越低</div>
                </div>
            </div>
            

            
    `;
    
    comparisonResult.innerHTML = comparisonHTML;
    comparisonSection.style.display = 'block';
    comparisonSection.scrollIntoView({ behavior: 'smooth' });
}

function validateInputs() {
    const loanAmount = document.getElementById('loanAmount').value;
    const annualRate = document.getElementById('annualRate').value;
    
    if (loanAmount && annualRate) {
        generatePlanBtn.disabled = false;
    } else {
        generatePlanBtn.disabled = true;
    }
}

function validateStepRatio() {
    const stepRatio = document.getElementById('stepRatio').value;
    const stepAnnualRate = document.getElementById('stepAnnualRate').value;
    const stepType = document.getElementById('stepType').value;
    
    if (stepRatio && stepAnnualRate) {
        const ratios = stepRatio.split(':').map(r => parseFloat(r.trim()));
        const expectedLength = stepType === 'two' ? 2 : 3;
        
        if (ratios.length === expectedLength) {
            // 检查比例总和是否为10
            const totalRatio = ratios.reduce((sum, ratio) => sum + ratio, 0);
            if (Math.abs(totalRatio - 10) <= 0.01) { // 允许0.01的误差
                generateStepPlanBtn.disabled = false;
            } else {
                generateStepPlanBtn.disabled = true;
            }
        } else {
            generateStepPlanBtn.disabled = true;
        }
    } else {
        generateStepPlanBtn.disabled = false;
    }
}

function updateStepRatioPlaceholder() {
    const stepType = document.getElementById('stepType').value;
    const stepRatioInput = document.getElementById('stepRatio');
    
    if (stepType === 'two') {
        // 两阶：前两年和后一年
        stepRatioInput.placeholder = '请输入两个比例，如：8.00:2.00';
        stepRatioInput.value = '8.00:2.00';
    } else {
        // 三阶：每年为一阶
        stepRatioInput.placeholder = '请输入三个比例，如：4.00:4.00:2.00';
        stepRatioInput.value = '4.00:4.00:2.00';
    }
    
    // 重新验证
    validateStepRatio();
}

// 生成两阶方案（前两年和后一年）
function generateTwoStagePlan(ratios) {
    const loanAmount = parseFloat(document.getElementById('loanAmount').value);
    const stepAnnualRate = parseFloat(document.getElementById('stepAnnualRate').value) / 100;
    const repaymentMethod = document.getElementById('repaymentMethod').value;
    const monthlyRate = stepAnnualRate / 12;
    
    const firstStageRatio = ratios[0] / 10; // 前两年比例
    const secondStageRatio = ratios[1] / 10; // 后一年比例
    
    const firstStagePrincipal = loanAmount * firstStageRatio; // 前两年要还的本金
    const secondStagePrincipal = loanAmount * secondStageRatio; // 后一年要还的本金
    
    let plan = [];
    let remainingPrincipal = loanAmount;
    
    if (repaymentMethod === 'equal') {
        // 等额本息
        // 前24期（前两年）：起始本金40000，24期后还掉32000本金，还剩8000本金
        const targetRemainingAfter24 = loanAmount - firstStagePrincipal; // 24期后剩余本金
        
        // 计算前24期的每月还款金额
        const firstStagePayment = calculateMonthlyPaymentForTargetRemaining(loanAmount, targetRemainingAfter24, monthlyRate, 24);
        
        for (let month = 1; month <= 24; month++) {
            const interest = remainingPrincipal * monthlyRate;
            const principal = firstStagePayment - interest;
            
            plan.push({
                month: month,
                payment: firstStagePayment,
                principal: principal,
                interest: interest,
                remainingPrincipal: Math.max(0, remainingPrincipal - principal)
            });
            
            remainingPrincipal -= principal;
        }
        
        // 后12期（后一年）：剩余8000本金，12期还清
        const secondStagePayment = remainingPrincipal * (monthlyRate * Math.pow(1 + monthlyRate, 12)) / 
                                   (Math.pow(1 + monthlyRate, 12) - 1);
        
        for (let month = 25; month <= 36; month++) {
            const interest = remainingPrincipal * monthlyRate;
            const principal = secondStagePayment - interest;
            
            plan.push({
                month: month,
                payment: secondStagePayment,
                principal: principal,
                interest: interest,
                remainingPrincipal: Math.max(0, remainingPrincipal - principal)
            });
            
            remainingPrincipal -= principal;
        }
    } else {
        // 等额本金
        // 前24期（前两年）：每月还本金 = 32000 / 24
        const firstStageMonthlyPrincipal = firstStagePrincipal / 24;
        
        for (let month = 1; month <= 24; month++) {
            const interest = remainingPrincipal * monthlyRate;
            const payment = firstStageMonthlyPrincipal + interest;
            
            plan.push({
                month: month,
                payment: payment,
                principal: firstStageMonthlyPrincipal,
                interest: interest,
                remainingPrincipal: Math.max(0, remainingPrincipal - firstStageMonthlyPrincipal)
            });
            
            remainingPrincipal -= firstStageMonthlyPrincipal;
        }
        
        // 后12期（后一年）：每月还本金 = 8000 / 12
        const secondStageMonthlyPrincipal = secondStagePrincipal / 12;
        
        for (let month = 25; month <= 36; month++) {
            const interest = remainingPrincipal * monthlyRate;
            const payment = secondStageMonthlyPrincipal + interest;
            
            plan.push({
                month: month,
                payment: payment,
                principal: secondStageMonthlyPrincipal,
                interest: interest,
                remainingPrincipal: Math.max(0, remainingPrincipal - secondStageMonthlyPrincipal)
            });
            
            remainingPrincipal -= secondStageMonthlyPrincipal;
        }
    }
    
    return plan;
}

// 生成三阶方案（每年为一阶）
function generateThreeStagePlan(ratios) {
    const loanAmount = parseFloat(document.getElementById('loanAmount').value);
    const stepAnnualRate = parseFloat(document.getElementById('stepAnnualRate').value) / 100;
    const repaymentMethod = document.getElementById('repaymentMethod').value;
    const monthlyRate = stepAnnualRate / 12;
    
    const firstYearRatio = ratios[0] / 10; // 第一年比例
    const secondYearRatio = ratios[1] / 10; // 第二年比例
    const thirdYearRatio = ratios[2] / 10; // 第三年比例
    
    const firstYearPrincipal = loanAmount * firstYearRatio; // 第一年要还的本金
    const secondYearPrincipal = loanAmount * secondYearRatio; // 第二年要还的本金
    const thirdYearPrincipal = loanAmount * thirdYearRatio; // 第三年要还的本金
    
    let plan = [];
    let remainingPrincipal = loanAmount;
    
    if (repaymentMethod === 'equal') {
        // 等额本息
        // 第1-12期（第一年）：起始本金40000，12期后还掉第一年比例的本金
        const targetRemainingAfter12 = loanAmount - firstYearPrincipal; // 12期后剩余本金
        const firstYearPayment = calculateMonthlyPaymentForTargetRemaining(loanAmount, targetRemainingAfter12, monthlyRate, 12);
        
        for (let month = 1; month <= 12; month++) {
            const interest = remainingPrincipal * monthlyRate;
            const principal = firstYearPayment - interest;
            
            plan.push({
                month: month,
                payment: firstYearPayment,
                principal: principal,
                interest: interest,
                remainingPrincipal: Math.max(0, remainingPrincipal - principal)
            });
            
            remainingPrincipal -= principal;
        }
        
        // 第13-24期（第二年）：剩余本金，12期后还掉第二年比例的本金
        const targetRemainingAfter24 = remainingPrincipal - secondYearPrincipal; // 24期后剩余本金
        const secondYearPayment = calculateMonthlyPaymentForTargetRemaining(remainingPrincipal, targetRemainingAfter24, monthlyRate, 12);
        
        for (let month = 13; month <= 24; month++) {
            const interest = remainingPrincipal * monthlyRate;
            const principal = secondYearPayment - interest;
            
            plan.push({
                month: month,
                payment: secondYearPayment,
                principal: principal,
                interest: interest,
                remainingPrincipal: Math.max(0, remainingPrincipal - principal)
            });
            
            remainingPrincipal -= principal;
        }
        
        // 第25-36期（第三年）：剩余本金，12期后还清
        const thirdYearPayment = remainingPrincipal * (monthlyRate * Math.pow(1 + monthlyRate, 12)) / 
                                 (Math.pow(1 + monthlyRate, 12) - 1);
        
        for (let month = 25; month <= 36; month++) {
            const interest = remainingPrincipal * monthlyRate;
            const principal = thirdYearPayment - interest;
            
            plan.push({
                month: month,
                payment: thirdYearPayment,
                principal: principal,
                interest: interest,
                remainingPrincipal: Math.max(0, remainingPrincipal - principal)
            });
            
            remainingPrincipal -= principal;
        }
    } else {
        // 等额本金
        // 第1-12期（第一年）：每月还本金 = 第一年本金 / 12
        const firstYearMonthlyPrincipal = firstYearPrincipal / 12;
        
        for (let month = 1; month <= 12; month++) {
            const interest = remainingPrincipal * monthlyRate;
            const payment = firstYearMonthlyPrincipal + interest;
            
            plan.push({
                month: month,
                payment: payment,
                principal: firstYearMonthlyPrincipal,
                interest: interest,
                remainingPrincipal: Math.max(0, remainingPrincipal - firstYearMonthlyPrincipal)
            });
            
            remainingPrincipal -= firstYearMonthlyPrincipal;
        }
        
        // 第13-24期（第二年）：每月还本金 = 第二年本金 / 12
        const secondYearMonthlyPrincipal = secondYearPrincipal / 12;
        
        for (let month = 13; month <= 24; month++) {
            const interest = remainingPrincipal * monthlyRate;
            const payment = secondYearMonthlyPrincipal + interest;
            
            plan.push({
                month: month,
                payment: payment,
                principal: secondYearMonthlyPrincipal,
                interest: interest,
                remainingPrincipal: Math.max(0, remainingPrincipal - secondYearMonthlyPrincipal)
            });
            
            remainingPrincipal -= secondYearMonthlyPrincipal;
        }
        
        // 第25-36期（第三年）：每月还本金 = 第三年本金 / 12
        const thirdYearMonthlyPrincipal = thirdYearPrincipal / 12;
        
        for (let month = 25; month <= 36; month++) {
            const interest = remainingPrincipal * monthlyRate;
            const payment = thirdYearMonthlyPrincipal + interest;
            
            plan.push({
                month: month,
                payment: payment,
                principal: thirdYearMonthlyPrincipal,
                interest: interest,
                remainingPrincipal: Math.max(0, remainingPrincipal - thirdYearMonthlyPrincipal)
            });
            
            remainingPrincipal -= thirdYearMonthlyPrincipal;
        }
    }
    
    return plan;
}

// 计算指定剩余本金下的每月还款金额
function calculateMonthlyPaymentForTargetRemaining(initialPrincipal, targetRemaining, monthlyRate, months) {
    // 使用等额本息公式，但目标是期数后剩余指定本金
    // 公式：月还款 = (初始本金 - 目标剩余本金 * (1+月利率)^(-期数)) * 月利率 / (1 - (1+月利率)^(-期数))
    const discountFactor = Math.pow(1 + monthlyRate, -months);
    const monthlyPayment = (initialPrincipal - targetRemaining * discountFactor) * monthlyRate / (1 - discountFactor);
    return monthlyPayment;
}

// 打印方案功能
function downloadPlan() {
    // 检查是否有数据可以打印
    if (!originalPlan && !stepPlan) {
        alert('请先生成还款计划或阶梯贷方案');
        return;
    }
    
    // 直接调用打印功能
    printAsPDF();
}



// 打印为PDF
function printAsPDF() {
    // 隐藏不需要打印的元素
    const elementsToHide = document.querySelectorAll('.input-section, .analysis-section');
    elementsToHide.forEach(el => el.style.display = 'none');
    
    // 添加打印样式
    const printStyle = document.createElement('style');
    printStyle.textContent = `
        @media print {
            /* 基础设置 */
            body { margin: 0; }
            .btn { display: none; }
            header { display: none !important; }
            
            /* 设置页面边距 */
            @page {
                margin: 13mm 15mm 13mm 15mm;
            }
            
            /* 彻底清除所有可能的顶部间距 */
            .container { padding: 0 !important; }
            .main-content { 
                padding: 0 !important; 
                margin: 0 !important;
                background: none !important;
                border-radius: 0 !important;
                box-shadow: none !important;
            }
            
            /* 隐藏所有输入区域 */
            .input-section { display: none !important; }
            .analysis-section { display: none !important; }
            
            /* 方案区域基础样式 */
            .plan-section {
                background: none !important;
                border: none !important;
                border-top: 5px solid #28a745 !important;
                box-shadow: none !important;
                padding: 0 !important;
                margin: 0 !important;
            }
            
            .plan-section:first-of-type {
                margin-top: 0 !important;
                padding-top: 0 !important;
            }
            
            /* 分页控制 */
            .plan-section.expanded { 
                page-break-after: always; 
                page-break-inside: avoid;
                margin-bottom: 0 !important;
                padding-bottom: 0 !important;
            }
            
            .plan-section:not(.expanded) {
                margin-bottom: 15px !important;
                page-break-after: avoid;
                page-break-inside: avoid;
            }
            
            /* 标题样式统一 */
            .plan-section h3 {
                margin-bottom: 8px !important;
                font-size: 1rem !important;
                line-height: 1.1 !important;
            }
            
            /* 表格样式统一 */
            .repayment-table {
                font-size: 0.8rem !important;
                line-height: 1.2 !important;
            }
            
            .repayment-table th,
            .repayment-table td {
                padding: 4px 3px !important;
                line-height: 1.2 !important;
            }
            
            /* 合计行样式统一 */
            .total-row td {
                padding: 3px 3px !important;
                line-height: 1.0 !important;
            }
            
            .total-row {
                border-top: 1px solid #ddd !important;
            }
            
            /* 省略号行紧凑显示 */
            .ellipsis-row td {
                padding: 2px !important;
                font-size: 0.75rem !important;
            }
            
            /* 对比分析样式 */
            .comparison-group {
                page-break-inside: avoid;
                display: grid !important;
                grid-template-columns: 1fr 1fr !important;
                background: none !important;
                border: none !important;
                box-shadow: none !important;
                padding: 0 !important;
                margin: 0 !important;
                border-top: 5px solid #667eea !important;
            }
            
            .comparison-group:first-of-type { 
                page-break-before: always;
            }
            
            /* 去除所有阴影 */
            * { box-shadow: none !important; }
        }
    `;
    document.head.appendChild(printStyle);
    
    // 触发打印
    window.print();
    
    // 恢复显示
    elementsToHide.forEach(el => el.style.display = 'block');
    
    // 移除打印样式
    document.head.removeChild(printStyle);
}






